from PySide6 import QtWidgets, QtCore
from PySide6.QtCore import Qt, QSize
from PySide6.QtWidgets import QWidget, QVBoxLayout, QTableWidget, QPushButton, QInputDialog, QTableWidgetItem, \
    QApplication, QHeaderView
from PySide6.QtGui import QFont
from log_excel import write_data

from ui_LogViewer import Ui_LogViewer
import resource.rc_resource

class LogWindow(QWidget, Ui_LogViewer):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle('日志')
        # self.setMinimumSize(800, 600)
        self.center()
        # self.layout = QVBoxLayout()

        self.frame_bg.installEventFilter(self)

        self.setWindowFlag(Qt.WindowType.FramelessWindowHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)

        qss = QtCore.QFile(":/qss/LogViewer.qss")
        qss.open(QtCore.QIODevice.ReadOnly)
        self.setStyleSheet(str(qss.readAll(), 'utf-8'))

        # 设置表格属性
        # self.table = QTableWidget()
        self.headers = ['点位', '时间', '状态']
        self.table.horizontalHeader().setFixedHeight(60)
        self.table.setHorizontalHeaderLabels(self.headers)
        self.table.horizontalHeader().sectionClicked.connect(self.filter_column)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Fixed)
        self.table.setColumnWidth(0, 300)
        self.table.setColumnWidth(1, 400)
        self.table.setColumnWidth(2, 300)

        # 设置返回按钮
        # self.reset_button = QPushButton('返回')
        # self.reset_button.clicked.connect(self.reset_table)
        self.reset_button.clicked.connect(self.close)

        # 调整布局
        # self.layout.addWidget(self.table, alignment=Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter)
        # self.layout.addWidget(self.reset_button)
        # self.setLayout(self.layout)

        self.fill_table('./logs')

    def reset_table(self):
        for row in range(self.table.rowCount()):
            self.table.setRowHidden(row, False)

    def filter_column(self, index):
        if self.headers[index] == '时间':
            options = sorted(
                set(self.table.item(row, index).text().split(' ')[0] for row in range(self.table.rowCount())))
        else:
            options = sorted(set(self.table.item(row, index).text() for row in range(self.table.rowCount())))
        filter_text, ok = QInputDialog.getItem(self, f"筛选 {self.headers[index]}", f"筛选 {self.headers[index]}:",
                                               options, 0, False)
        if ok and filter_text:
            for row in range(self.table.rowCount()):
                item = self.table.item(row, index)
                if self.headers[index] == '时间':
                    item_text = item.text().lower().split(' ')[0]
                else:
                    item_text = item.text().lower()

                if item and filter_text.lower() == item_text:
                    if not self.table.isRowHidden(row):
                        self.table.setRowHidden(row, False)
                else:
                    self.table.setRowHidden(row, True)

    def set_table_size(self):
        # self.table.setFixedSize(800, 600)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Fixed)
        self.table.setColumnWidth(0, 250)
        self.table.setColumnWidth(1, 500)
        self.table.setColumnWidth(2, 250)

    def fill_table(self, path):
        data = write_data(path)
        if (data.empty):
            # logger.info("无近七天日志")
            return
        data = data.sort_values('时间', ascending=False)
        num_rows, num_cols = data.shape
        self.table.setRowCount(num_rows)
        self.table.setColumnCount(num_cols)
        self.table.setHorizontalHeaderLabels(data.columns)
        for i in range(num_rows):
            self.table.setRowHeight(i, 50)
            for j in range(num_cols):
                item = QTableWidgetItem(str(data.iloc[i, j]))
                item.setTextAlignment(Qt.AlignCenter)
                font = item.font()
                font.setPixelSize(18)
                item.setFont(font)
                self.table.setItem(i, j, item)
        self.set_table_size()

    def center(self):
        # 获取屏幕的几何信息
        available_geometry = QApplication.primaryScreen().availableGeometry()
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(available_geometry.center())
        self.move(window_geometry.topLeft())

    def eventFilter(self, watched, event):
        if watched == self.frame_bg:
            if event.type() == QtCore.QEvent.Type.MouseButtonPress:
                if event.buttons() and QtCore.Qt.MouseButton.LeftButton:
                    self.windowHandle().startSystemMove()
        return super().eventFilter(watched, event)
